/* eslint-disable max-len */
const { Service } = require('egg')
const puppeteer = require('puppeteer')
const url = require('url')
const CryptoJS = require('crypto-js')

/* 加密 */
function getAesString(data, key, iv) {
  const encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  })
  return encrypted.toString()
}

// 加密
function getAES(data) {
  const key = 'rKLXUF-KT_Gm6qmu' // 密钥
  const iv = 'rKLXUF-KT_Gm6qmu'
  const encrypted = getAesString(data, key, iv) // 密文
  return encrypted
}

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data
      /* * 0. 请求门户主页 */
      const indexUrl = 'https://webvpn.jsu.edu.cn/login'
      const indexRes = await ctx.curl(indexUrl, {
        method: 'GET',
        headers: {
          Host: 'webvpn.jsu.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        },
      })
      const setCookie = indexRes.headers['set-cookie'] ? indexRes.headers['set-cookie'].map((e) => e.split(';')[0])[0] : ''
      console.log('setCookie', setCookie)
      console.log('1', indexRes.status, indexRes.headers.location)

      /* * 2. 重定向1，获取新门户地址 */
      const RedirectRes1 = await ctx.curl(`https://webvpn.jsu.edu.cn${indexRes.headers.location}`, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.jsu.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      console.log('2', indexRes.status, RedirectRes1.headers.location)

      /* * 2. 重定向2，模拟访问门户 */
      const RedirectRes2 = await ctx.curl(RedirectRes1.headers.location, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.jsu.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
        // followRedirect: true, // 允许重定向，模拟登录成功的关键操作
      })
      console.log('3', RedirectRes2.status)

      const parsedUrl = url.parse(RedirectRes1.headers.location.replace('#/', ''), true) // 使用url.parse解析URL
      const queryParams = { ...parsedUrl.query }
      // console.log('queryParams', queryParams)

      /* * 3.登录 */
      // eslint-disable-next-line max-len
      const loginRes = await ctx.curl('https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421e0f6528f693a7b45300d8db9d6562d/login/casLogin?vpn-12-o2-pass.jsu.edu.cn', {
        method: 'POST',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.jsu.edu.cn',
          Referer: 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421e0f6528f693a7b45300d8db9d6562d/',
          Token: getAES(`Bz6n8VwRQRG43tVxrWVxPw${new Date().getTime()}`),
          'Content-Type': 'application/json',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
        data: {
          account: sid,
          redirect_uri: 'https%3A%2F%2Fwebvpn.jsu.edu.cn%2Flogin%3Foauth_login%3Dtrue',
          belongClientId: queryParams.client_id,
          sn: queryParams.sn,
          ticket: pwd,
          type: 'pwd',
        },
        // dataType: 'json',
      })
      console.log('4', loginRes.status, loginRes.data.toString())

      if (loginRes.status === 200) {
        const data = JSON.parse(loginRes.data.toString())
        if (data.code === 200) {
          console.log('data', data)
          /* 登录成功，开始重定向激活cookie */
          const RedirectRes3 = await ctx.curl(data.data.replace('https://portal.jsu.edu.cn', 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421e0f85388263c265a6d1dc7a99c406d36f9'), {
            method: 'GET',
            headers: {
              Cookie: setCookie,
              Host: 'webvpn.jsu.edu.cn',
              Referer: 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421e0f6528f693a7b45300d8db9d6562d/',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
            },
          })
          console.log('4', RedirectRes3.status, RedirectRes3.headers.location)

          const RedirectRes4 = await ctx.curl(RedirectRes3.headers.location, {
            method: 'GET',
            headers: {
              Cookie: setCookie,
              Host: 'webvpn.jsu.edu.cn',
              Referer: 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421e0f6528f693a7b45300d8db9d6562d/',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
            },
          })
          console.log('5', RedirectRes4.status, RedirectRes4.headers.location)

          const RedirectRes5 = await ctx.curl(`https://webvpn.jsu.edu.cn${RedirectRes4.headers.location}`, {
            method: 'GET',
            headers: {
              Cookie: setCookie,
              Host: 'webvpn.jsu.edu.cn',
              Referer: 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421e0f6528f693a7b45300d8db9d6562d/',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
            },
          })
          console.log('6', RedirectRes5.status, RedirectRes5.headers.location)

          const RedirectRes6 = await ctx.curl(`https://webvpn.jsu.edu.cn${RedirectRes5.headers.location}`, {
            method: 'GET',
            headers: {
              Cookie: setCookie,
              Host: 'webvpn.jsu.edu.cn',
              Referer: 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421e0f6528f693a7b45300d8db9d6562d/',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
            },
          })
          console.log('7', RedirectRes6.status, RedirectRes6.headers.location)
          /* end */

          // const RedirectRes7 = await ctx.curl(`https://webvpn.jsu.edu.cn${RedirectRes6.headers.location}`, {
          //   method: 'GET',
          //   headers: {
          //     Cookie: setCookie,
          //     Host: 'webvpn.jsu.edu.cn',
          //     Referer: 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421e0f6528f693a7b45300d8db9d6562d/',
          //     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
          //   },
          // })
          // console.log('8', RedirectRes7.status, RedirectRes7.headers.location)

          // const RedirectRes8 = await ctx.curl(RedirectRes7.headers.location, {
          //   method: 'GET',
          //   headers: {
          //     Host: RedirectRes7.headers.location.replace('https://', '').replace('cn/', 'cn'),
          //     Referer: 'https://webvpn.jsu.edu.cn/',
          //     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
          //   },
          // })
          // console.log('9', RedirectRes8.status, RedirectRes8.headers.location)

          // const RedirectRes9 = await ctx.curl(RedirectRes8.headers.location, {
          //   method: 'GET',
          //   headers: {
          //     Cookie: setCookie,
          //     Host: 'webvpn.jsu.edu.cn',
          //     Referer: 'https://webvpn.jsu.edu.cn/',
          //     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
          //   },
          // })
          // console.log('10', RedirectRes9.status, RedirectRes9.data.toString())
          // console.log('10', RedirectRes9.status)

          /* 登入教务系统 */
          const RedirectRes7 = await ctx.curl('https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421fae05988693a7b45300d8db9d6562d/Logon.do?method=logonBymysfxy', {
            method: 'GET',
            headers: {
              Cookie: setCookie,
              Host: 'webvpn.jsu.edu.cn',
              Referer: 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421f9b94b8f327e6d546b468aa2/home/simple',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
            },
          })
          console.log('8', RedirectRes7.status, RedirectRes7.headers.location)

          const RedirectRes8 = await ctx.curl(RedirectRes7.headers.location, {
            method: 'GET',
            headers: {
              Cookie: setCookie,
              Host: 'webvpn.jsu.edu.cn',
              Referer: 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421f9b94b8f327e6d546b468aa2/home/simple',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
            },
          })
          console.log('9', RedirectRes8.status, RedirectRes8.headers.location)

          const RedirectRes9 = await ctx.curl(RedirectRes8.headers.location, {
            method: 'GET',
            headers: {
              Cookie: setCookie,
              Host: 'webvpn.jsu.edu.cn',
              Referer: 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421f9b94b8f327e6d546b468aa2/home/simple',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
            },
          })
          console.log('10', RedirectRes9.status, RedirectRes9.headers.location)

          const RedirectRes10 = await ctx.curl(RedirectRes9.headers.location, {
            method: 'GET',
            headers: {
              Cookie: setCookie,
              Host: 'webvpn.jsu.edu.cn',
              Referer: 'https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421f9b94b8f327e6d546b468aa2/home/simple',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
            },
          })
          console.log('11', RedirectRes10.status, RedirectRes10.headers.location)
          /* end */

          return { setCookie, status: 302 }
        }
        if (data.code === 401) {
          return { setCookie, status: 200 }
        }
        return { setCookie: '', status: 500 }
      }

      return { setCookie, status: 302 }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }

  /**
   * * 模拟登录，自动化获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookieAU() {
    let browser
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data
      // browser = await puppeteer.launch({ headless: false, args: ['--start-maximized'], defaultViewport: { width: 1920, height: 1080 } })
      browser = await puppeteer.launch({ headless: true, args: ['--window-size=1920,1080'], defaultViewport: { width: 1920, height: 1080 } })

      const page = await browser.newPage()
      await page.goto('https://i.jsu.edu.cn/', { waitUntil: 'domcontentloaded' })

      // 输入用户名
      await page.type('input[type="text"]', sid, { delay: 50 }) // 替换'#usernameInput'为实际的用户名输入框的选择器
      // 输入密码
      await page.type('input[type="password"]', pwd, { delay: 50 }) // 替换'#passwordInput'为实际的密码输入框的选择器
      // 点击登录按钮
      page.click('.el-button')
      await page.waitForSelector('.item-list-link')

      page.goto('https://webvpn.jsu.edu.cn/https/77726476706e69737468656265737421fae05988693a7b45300d8db9d6562d/Logon.do?method=logonBymysfxy')
      await page.waitForNavigation({ waitUntil: 'domcontentloaded' })

      const cookie = (await page.cookies()).map((item) => `${item.name}=${item.value}`).join('; ')
      console.log('cookie', cookie)
      await browser.close()

      return { setCookie: cookie, status: 302 }
    } catch (err) {
      await browser.close()
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
